package com.ba.grain;

import java.io.File;
import java.io.IOException;

import org.w3c.dom.Node;

import util.RequestResponse;
import util.XMLParser;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Toast;

public class ExportActivity extends RecordActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mBtn.setText("导出");
	}

	@Override
	public void onClick(View v) {

		if (v == mBtn) {
			export();
		}
		super.onClick(v);
	}

	void export() {
		File dir = CollectActivity.makeRootDir();
		File file = new File(dir, String.format("%s.xml", G.sUser.loginName));
		try {
			file.createNewFile();

			XMLParser parser = new XMLParser();
			parser.setEncoder(XMLParser.UTF_8);
			// resp[0] = parser.addTag(REQ, NAME, CHECK_USER, PARAM, userID,
			// PASSWORD, pwd);
			Node root = parser.addTag("Records", "LoginName",
					G.sUser.loginName, "CNName", G.sUser.cnName);

			SparseBooleanArray sba = getListView().getCheckedItemPositions();
			for (int i = 0; i < sba.size(); i++) {
				int key = sba.keyAt(i);
				if (sba.get(key)) {
					ListItem li = (ListItem) getListView().getItemAtPosition(
							key);
					parser.add_tag_parent(root, "Record", "Value",
							li.toString());
				}
			}
			String val = parser.toString();
			Log.d(TAG, val);
			RequestResponse.save2File(parser.toString(), file.getPath(), false);
			Toast.makeText(this, String.format("记录已成功导出至%s", file.getPath()),
					Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
}
